<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    width="800px"
    :close-on-click-modal="false"
    :before-close="handleClose"
  >
    <el-form ref="tableEdit" :model="table" :rules="rules" label-width="130px">
      <el-card header="基础配置">
        <el-form-item label="标题" prop="Title">
          <el-input
            v-model="table.Title"
            :maxlength="50"
            placeholder="标题"
            :clearable="true"
          />
        </el-form-item>
        <el-form-item label="是否隐藏标题" prop="IsHidden">
          <el-switch
            v-model="table.IsHidden"
            active-text="隐藏"
            inactive-text="显示"
          />
        </el-form-item>
        <el-form-item v-if="tableType == 0" label="每行列数" prop="ColNum">
          <el-input-number
            v-model="table.ColNum"
            :clearable="true"
            :precision="0"
            :min="1"
            :max="6"
            placeholder="每行列数"
          />
        </el-form-item>
        <el-form-item v-if="tableType == 0" label="表单域标签的位置" prop="LabelPosition">
          <el-select
            v-model="table.LabelPosition"
            placeholder="表单域标签的位置"
            :clearable="true"
          >
            <el-option label="左" :value="0" />
            <el-option label="顶部" :value="1" />
            <el-option label="右" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="tableType == 0 && table.LabelPosition != 1" label="Label宽度" prop="LabelWidth">
          <el-input-number
            v-model="table.LabelWidth"
            :clearable="true"
            :precision="0"
            :min="80"
            :max="200"
            placeholder="每行列数"
          />
        </el-form-item>
        <el-form-item label="数据来源" prop="SourceKey">
          <el-select
            v-model="table.SourceKey"
            placeholder="数据源"
            :clearable="true"
            @change="sourceChange"
          >
            <el-option
              v-for="item in formSource"
              :key="item.Id"
              :label="item.Title"
              :value="item.SourceKey"
            />
          </el-select>
        </el-form-item>
      </el-card>
    </el-form>
    <dataSourceEdit
      v-if="sourConfigs && sourConfigs.length > 0"
      ref="dataSource"
      v-model="sourceSet"
      :template="sourConfigs"
      style="margin-top: 10px"
    />
    <el-card v-if="tableType === 1" header="列表配置" style="margin-top: 10px">
      <el-form ref="tableSetEdit" :model="tableSet" label-width="120px">
        <el-form-item label="是否显示序号" prop="IsShowNo">
          <el-switch
            v-model="tableSet.IsShowNo"
            active-text="是"
            inactive-text="否"
          />
        </el-form-item>
        <el-form-item label="列表行生成方式" prop="RowGenerateMode">
          <enumItem
            v-model="tableSet.RowGenerateMode"
            :dic-key="EnumDic.RowGenerateMode"
            placeholder="列表行生成方式"
            sys-head="form"
          />
        </el-form-item>
        <el-form-item
          v-if="tableSet.RowGenerateMode === 1"
          label="固定生成的行数"
          prop="FixedRowNum"
        >
          <el-input-number
            v-model="tableSet.FixedRowNum"
            :clearable="true"
            placeholder="固定生成的行数"
          />
        </el-form-item>
        <div v-else-if="tableSet.RowGenerateMode === 3">
          <el-form-item label="每组生成的行数" prop="FillRowNum">
            <el-input-number
              v-model="tableSet.FillRowNum"
              :clearable="true"
              :min="0"
              placeholder="每组数据生成的行数"
              @change="initFillRow"
            />
          </el-form-item>
          <el-form-item label="填充的行">
            <p>
              <el-cascader
                v-model="fillCol"
                placeholder="选择填充的列"
                :clearable="true"
                :props="{
                  emitPath: false
                }"
                :options="tableCols"
              />
              <el-button
                style="margin-left: 10px"
                type="primary"
                size="mini"
                icon="el-icon-plus"
                @click="addColItem"
              >添加列</el-button>
            </p>
            <el-table :data="fillColumn" :border="true" style="width: 100%">
              <el-table-column
                prop="index"
                label="序号"
                type="index"
                width="50"
              />
              <el-table-column
                v-for="col in fillColList"
                :key="col.ColName"
                :prop="col.ColName"
                :label="col.ColTitle"
                width="180"
              >
                <template slot="header" slot-scope="scope">
                  <span>{{ scope.column.label }}</span>
                  <el-button
                    style="float: right"
                    type="danger"
                    size="mini"
                    icon="el-icon-delete"
                    circle
                    @click="dropCol(col)"
                  />
                </template>
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row[col.ColName]"
                    placeholder="填充值"
                    :clearable="true"
                  />
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </div>
        <el-form-item
          v-else-if="tableSet.RowGenerateMode === 2"
          label="生成行依据的列"
          prop="GenerateCol"
        >
          <el-cascader
            v-model="generateCol"
            placeholder="自动生成行依据的列"
            :props="{
              emitPath: true,
            }"
            :options="columns"
          />
        </el-form-item>
        <el-form-item label="是否分页" prop="IsPaging">
          <el-switch
            v-model="tableSet.IsPaging"
            active-text="是"
            inactive-text="否"
          />
        </el-form-item>
        <el-form-item label="每页行数" prop="PageSize">
          <el-input-number
            v-model="tableSet.PageSize"
            :disabled="!tableSet.IsPaging"
            :clearable="true"
            placeholder="每页行数"
          />
        </el-form-item>
        <el-form-item label="是否行验证" prop="IsRowCheck">
          <el-switch
            v-model="tableSet.IsRowCheck"
            active-text="是"
            inactive-text="否"
          />
        </el-form-item>
      </el-form>
    </el-card>
    <div slot="footer" style="text-align: center">
      <el-button type="primary" @click="save">保存</el-button>
      <el-button @click="reset">重置</el-button>
    </div>
  </el-dialog>
</template>

<script>
import * as tableApi from '@/customForm/api/table'
import { DictItemDic, ControlType, EnumDic } from '@/customForm/config/formConfig'
import { Gets } from '@/customForm/api/formSource'
import dataSourceEdit from './dataSourceEdit.vue'
export default {
  components: {
    dataSourceEdit
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    formBody: {
      type: Array,
      default: () => []
    },
    tableBody: {
      type: Object,
      default: null
    },
    id: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      DictItemDic,
      EnumDic,
      title: '编辑表单信息',
      table: {},
      tableSet: {},
      fillCol: null,
      columns: [],
      generateCol: null,
      formSource: [],
      sourConfigs: [],
      sourKey: null,
      sourSet: null,
      sourceSet: {},
      fillColList: [],
      tableCols: [],
      fillColumn: [],
      rules: {
        Title: [
          {
            required: true,
            message: '标题不能为空！',
            trigger: 'blur'
          }
        ]
      },
      tableType: 0
    }
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.reset()
        }
      },
      immediate: true
    }
  },
  mounted() {},
  methods: {
    async initSource() {
      this.formSource = await Gets(this.tableType)
      if (this.table.SourceKey != null) {
        this.sourceChange()
      }
    },
    dropCol(col) {
      const index = this.fillColList.findIndex((a) => a.ColId === col.ColId)
      this.fillColList.splice(index, 1)
    },
    sourceChange() {
      const config = this.formSource.find(
        (a) => a.SourceKey === this.table.SourceKey
      )
      if (config) {
        this.sourceSet = config.SourceKey === this.sourKey ? this.sourSet : {}
        this.sourConfigs = config.Template
      } else {
        this.sourceSet = {}
        this.sourConfigs = null
      }
    },
    addColItem() {
      if (this.fillCol == null || this.fillCol === '') {
        return
      } else if (
        this.fillColList.findIndex((a) => a.ColName === this.fillCol) !== -1
      ) {
        this.$message({
          message: '列名重复!',
          type: 'error'
        })
        return
      }
      const val = this.getColumn(this.fillCol, this.tableBody.Columns)
      this.fillColList.push(val)
      this.initFillRow()
    },
    initFillRow() {
      if (
        this.tableSet.FillRowNum === 0
      ) {
        this.fillColumn = []
        return
      }
      const list = []
      for (let i = 0; i < this.tableSet.FillRowNum; i++) {
        const data = {}
        const sour = this.fillColumn[i]
        this.fillColList.forEach((a) => {
          data[a.ColName] = sour ? sour[a.ColName] : null
        })
        list.push(data)
      }
      this.fillColumn = list
    },
    getColumn(val, columns) {
      for (let i = 0; i < columns.length; i++) {
        const col = columns[i]
        if (col.ColName === val) {
          return col
        } else if (col.Children && col.Children.length > 0) {
          const t = this.getColumn(val, col.Children)
          if (t != null) {
            return t
          }
        }
      }
      return null
    },
    initTable(res) {
      if (res.TableSet == null) {
        this.tableSet = {
          RowGenerateMode: 0,
          GenerateCol: null,
          FixedRowNum: null,
          FillRowNum: null,
          IsPaging: false,
          PageSize: null,
          IsRowCheck: false
        }
        this.fillColList = []
        this.fillColumn = []
      } else {
        this.tableSet = {
          RowGenerateMode: res.TableSet.RowGenerateMode,
          FixedRowNum: res.TableSet.FixedRowNum,
          FillRowNum: res.TableSet.FillRowNum,
          IsPaging: res.TableSet.IsPaging,
          PageSize: res.TableSet.PageSize,
          IsRowCheck: res.TableSet.IsRowCheck,
          IsShowNo: res.TableSet.IsShowNo
        }
        this.fillColList = []
        this.fillColumn = []
        if (this.tableSet.RowGenerateMode === 2) {
          if (res.TableSet.GenerateCol) {
            this.generateCol = [res.TableSet.TableId, res.TableSet.GenerateCol]
          }
        } else if (this.tableSet.RowGenerateMode === 3) {
          const cols = []
          const list = []
          res.TableSet.FillColumn.forEach((a) => {
            list.push(a)
            const keys = Object.keys(a)
            keys.forEach((c) => {
              if (cols.findIndex((b) => b.ColName === c) === -1) {
                const col = this.getColumn(c, this.tableBody.Columns)
                if (col != null) {
                  cols.push(col)
                }
              }
            })
          })
          this.fillColList = cols
          this.fillColumn = list
        }
      }
    },
    async reset() {
      const res = await tableApi.Get(this.id)
      this.tableType = res.TableType
      this.sourKey = res.SourceKey
      this.sourSet = res.SourceSet
      this.sourceSet = null
      this.sourConfigs = []
      if (this.tableType === 1) {
        this.initColumns()
        this.initFllCol()
        this.$nextTick(function() {
          this.initTable(res)
        })
      }
      this.initSource()
      this.table = {
        Title: res.Title,
        IsHidden: res.IsHidden,
        ColNum: res.ColNum,
        SourceKey: res.SourceKey,
        LabelWidth: res.LabelWidth,
        LabelPosition: res.LabelPosition
      }
    },
    initFllCol() {
      const table = this.formBody.find(a => a.Id === this.id)
      if (table == null) {
        return
      }
      const cols = []
      table.Columns.forEach(a => {
        const col = {
          label: a.ColTitle,
          value: a.ColName
        }
        if (a.Children != null && a.Children.length > 0) {
          col.children = []
          this.initCols(a.Children, col)
        } else {
          col.label = a.ColTitle + '(' + a.ColName + ')'
        }
        cols.push(col)
      })
      this.tableCols = cols
    },
    initCols(cols, t) {
      cols.forEach(a => {
        const col = {
          label: a.ColTitle,
          value: a.ColName
        }
        if (a.Columns != null && a.Columns.length > 0) {
          col.children = []
          this.initCols(a.Columns, col)
        } else {
          col.label = a.ColTitle + '(' + a.ColName + ')'
        }
        t.children.push(col)
      })
    },
    initColumns() {
      const cols = []
      this.formBody.forEach((c) => {
        if (c.Columns == null || c.TableType === 1) {
          return
        }
        const children = c.Columns.filter(
          (a) => a.ColType === ControlType.number.value
        )
        if (children != null && children.length > 0) {
          cols.push({
            label: c.Title,
            value: c.Id,
            children: children.map((a) => {
              return {
                label: a.ColTitle + '(' + a.ColName + ')',
                value: a.ColName
              }
            })
          })
        }
      })
      this.columns = cols
    },
    handleClose() {
      this.$emit('update:visible', false)
      this.$emit('close', false)
    },
    format() {
      const data = {
        Title: this.table.Title,
        IsHidden: this.table.IsHidden,
        ColNum: this.table.ColNum,
        LabelWidth: this.table.LabelWidth,
        LabelPosition: this.table.LabelPosition,
        SourceKey: this.table.SourceKey
      }
      if (this.table.SourceKey !== null) {
        data.SourceSet = this.sourceSet
      }
      if (this.tableType === 1) {
        data.TableSet = {
          RowGenerateMode: this.tableSet.RowGenerateMode,
          FixedRowNum: this.tableSet.FixedRowNum,
          FillRowNum: this.tableSet.FillRowNum,
          IsPaging: this.tableSet.IsPaging,
          PageSize: this.tableSet.PageSize,
          IsRowCheck: this.tableSet.IsRowCheck,
          FillColumn: this.fillColumn,
          IsShowNo: this.tableSet.IsShowNo
        }
        if (this.tableSet.RowGenerateMode === 2 && this.generateCol != null && this.generateCol.length > 0) {
          data.TableSet.GenerateCol = this.generateCol[1]
          data.TableSet.TableId = this.generateCol[0]
        }
        if (this.tableSet.RowGenerateMode !== 3) {
          data.TableSet.FillColumn = []
        }
      }
      return data
    },
    async set() {
      const data = this.format()
      const isSet = await tableApi.Set(this.id, data)
      this.$emit('update:visible', false)
      this.$emit('close', isSet, this.table)
    },
    async save() {
      const valid = await this.$refs['tableEdit'].validate()
      if (valid === false) {
        return
      } else if (this.table.SourceKey != null && this.table.SourceKey !== '') {
        const res = await this.$refs.dataSource.validate()
        if (!res) {
          return
        }
      }
      this.set()
    }
  }
}
</script>
